﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Model;
using BLL;
using System.Text;

public partial class PersonInfo_WXUserReq :BasePage
{
    private Access access = new Access();
    WeiXinRequestBO pbo = new WeiXinRequestBO();
    private static int id;
    public string sr = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            if (GetQeuryString("para") == "update")
            {

                this.txtWeiXinNo.Enabled = false;
                //string id = GetQeuryString("openid");
                //WeiXinRequest user = pbo.GetModel(int.Parse(id));
                InitData();
            }
        }
    }


    private void InitData()
    {   
        txtWeiXinNo.Text = GetQeuryString("openid");
        //id = CurrentUserInfo.ID;
        string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Token() + "&openid=" + GetQeuryString("openid");
        string b = PostRequest(url);
        string[] a = b.Split('\"');
        if (a.Length == 35)
        {
            lblName.Text = a[9];     
        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        //WeiXinRequest user = GetEntity();
        if (GetQeuryString("para") == "update")
        {
            string Access_token = Token();

            var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
            string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""{1}""
    }
}";
            d = d.Replace("{0}", GetQeuryString("openid")).Replace("{1}", txtNR2.Text);
            var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);
            Response.Write(resMessage);
            //user.ID = Convert.ToInt32(GetQeuryString("id"));
            //pbo.Update(user);
            AlertAndCloseAndReloadParendDataGrid("保存成功！", "grid");
        }
    }




    /// <summary>
    /// HttpPost发送XML并返回响应
    /// </summary>
    /// <param name="postUrl"></param>
    /// <param name="xml"></param>        
    /// <param name="encoding"></param>         
    /// <returns>Response响应</returns>
    public static string HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding)
    {
        if (string.IsNullOrEmpty(postUrl))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException :  postUrl IsNullOrEmpty");
        }

        if (string.IsNullOrEmpty(postXml))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty");
        }

        var request = (HttpWebRequest)WebRequest.Create(postUrl);
        byte[] byteArray = encoding.GetBytes(postXml);
        request.ContentLength = byteArray.Length;
        request.Method = "post";
        request.ContentType = "text/xml";

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(byteArray, 0, byteArray.Length);
        }

        using (var responseStream = request.GetResponse().GetResponseStream())
        {
            return new StreamReader(responseStream, encoding).ReadToEnd();
        }
    }

    #region 私有方法
    private WeiXinRequest GetEntity()
    {
        WeiXinRequest user = new WeiXinRequest();
        if (GetQeuryString("para") == "update")
        {
            user = pbo.GetModel(Convert.ToInt32(GetQeuryString("openid")));
        }
        if (user.PicUrl != "")
            user.PicUrl = user.PicUrl + ";" + txtNR2.Text;
        else
            user.PicUrl = txtNR2.Text;
        return user;
    }
    private void InitData(WeiXinRequest CurrentUserInfo)
    {
        //txtNR.Text = CurrentUserInfo.Content;
        txtWeiXinNo.Text = CurrentUserInfo.FromUserName;
        id = CurrentUserInfo.ID;
        string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Token() + "&openid=" + CurrentUserInfo.FromUserName;
        string b = PostRequest(url);
        string[] a = b.Split('\"');
        if (a.Length == 35)
        {
            lblName.Text = a[9];
            //string c = @a[31].ToString();
            //c=c.Replace(@"//",@"").Replace(@"\\",@"");
            //c = c.Replace("\\/", "/");
            //Image1.ImageUrl = c;
            //sr = c;
        }
    }

    #endregion
    protected void Button2_Click(object sender, EventArgs e)
    {
        //    string FileName = file.FileName;
        //    string path = HttpContext.Current.Request.MapPath("Images/");

        //    if (!string.IsNullOrEmpty(FileName))
        //    {
        //        string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
        //        if ((extension.ToLower() == ".jpg"))
        //        {
        //            int fileSize = file.PostedFile.ContentLength;
        //            if (fileSize == 0)
        //            {
        //                base.AlertMessage("文件不存在！");
        //            }
        //            //else if (fileSize > 52100)
        //            //{
        //            //    AlertMessage("请上传50K以内的JPG格式照片");
        //            //}
        //            else
        //            {
        //                //if (File.Exists(path + CurrentUserInfo.ID + ".jpg"))
        //                //{
        //                //    File.Delete(path + CurrentUserInfo.ID + ".jpg");
        //                //}
        //                if (true)//限制大小为1M
        //                {
        //                    string guid = Guid.NewGuid().ToString();
        //                    file.SaveAs(path + guid + ".jpg");  //将文件上传到服务器
        //                    if (File.Exists(path + guid + ".jpg"))
        //                    {
        //                       // Image1.ImageUrl = "Images/" + guid + ".jpg";
        //                        txtPicUrl.Text = ConfigurationManager.AppSettings["ServerURL"] +"http://122.226.199.116/Vive/PersonInfo/Images/" + guid + ".jpg";
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            AlertMessage("请上传JPG格式图片!");
        //        }
        //    }
        //    else
        //    {
        //        AlertMessage("请选择文件.");
        //    }
    }
}